/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tenorclient;

import TransportLayer.IDataTransportable;
import TransportLayer.SrtpException;
import java.awt.Dimension;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JPanel;
import javax.swing.JTextArea;

/**
 *
 * @author Tomasz Nowak
 */
public class MainFrame extends javax.swing.JFrame
{
	DefaultListModel contactsListModel;
	Creditentials creditentials;
	final ExecutorService executorService;
	boolean serverRunned;

	public MainFrame()
	{
		executorService = Executors.newCachedThreadPool(Executors.defaultThreadFactory());
		serverRunned = false;

		contactsListModel = new DefaultListModel();
		for ( IContact iContact : Contacts.getInstance().getContacts() )
		{
			contactsListModel.addElement(iContact);
		}
		initComponents();
		contactList.setModel(contactsListModel);
		tabbedPane.removeAll();
		creditentials = Creditentials.getInstance();
	}

	/**
	 * This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	@SuppressWarnings( "unchecked" )
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents()
  {

    sendButton = new java.awt.Button();
    addressTextField = new javax.swing.JTextField();
    portTextField = new javax.swing.JTextField();
    nameTextField = new javax.swing.JTextField();
    addButton = new java.awt.Button();
    jScrollPane3 = new javax.swing.JScrollPane();
    contactList = new javax.swing.JList();
    tabbedPane = new javax.swing.JTabbedPane();
    settingsButton = new java.awt.Button();
    jScrollPane1 = new javax.swing.JScrollPane();
    messageTextArea = new javax.swing.JTextArea();
    listeningPort = new java.awt.TextField();
    startListeningButton = new java.awt.Button();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    sendButton.setLabel("Send");
    sendButton.addActionListener(new java.awt.event.ActionListener()
    {
      public void actionPerformed(java.awt.event.ActionEvent evt)
      {
        sendButtonActionPerformed(evt);
      }
    });

    addressTextField.setText("Address");
    addressTextField.addActionListener(new java.awt.event.ActionListener()
    {
      public void actionPerformed(java.awt.event.ActionEvent evt)
      {
        addressTextFieldActionPerformed(evt);
      }
    });

    portTextField.setText("Port");
    portTextField.addActionListener(new java.awt.event.ActionListener()
    {
      public void actionPerformed(java.awt.event.ActionEvent evt)
      {
        portTextFieldActionPerformed(evt);
      }
    });

    nameTextField.setText("Name");

    addButton.setLabel("Add");
    addButton.addActionListener(new java.awt.event.ActionListener()
    {
      public void actionPerformed(java.awt.event.ActionEvent evt)
      {
        addButtonActionPerformed(evt);
      }
    });

    contactList.setModel(new javax.swing.AbstractListModel()
    {
      String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
      public int getSize() { return strings.length; }
      public Object getElementAt(int i) { return strings[i]; }
    });
    contactList.addMouseListener(new java.awt.event.MouseAdapter()
    {
      public void mouseClicked(java.awt.event.MouseEvent evt)
      {
        contactListMouseClicked(evt);
      }
    });
    jScrollPane3.setViewportView(contactList);

    tabbedPane.setMaximumSize(new java.awt.Dimension(400, 300));
    tabbedPane.setMinimumSize(new java.awt.Dimension(400, 300));
    tabbedPane.setPreferredSize(new java.awt.Dimension(300, 400));

    settingsButton.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
    settingsButton.setLabel("Settings");
    settingsButton.setName(""); // NOI18N
    settingsButton.addActionListener(new java.awt.event.ActionListener()
    {
      public void actionPerformed(java.awt.event.ActionEvent evt)
      {
        settingsButtonActionPerformed(evt);
      }
    });

    messageTextArea.setColumns(20);
    messageTextArea.setRows(5);
    jScrollPane1.setViewportView(messageTextArea);

    listeningPort.setText("listening port");
    listeningPort.addActionListener(new java.awt.event.ActionListener()
    {
      public void actionPerformed(java.awt.event.ActionEvent evt)
      {
        listeningPortActionPerformed(evt);
      }
    });

    startListeningButton.setLabel("Start listening");
    startListeningButton.addActionListener(new java.awt.event.ActionListener()
    {
      public void actionPerformed(java.awt.event.ActionEvent evt)
      {
        startListeningButtonActionPerformed(evt);
      }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addGroup(layout.createSequentialGroup()
            .addGap(10, 10, 10)
            .addComponent(listeningPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(102, 102, 102)
            .addComponent(startListeningButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
          .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
              .addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 406, Short.MAX_VALUE)
              .addComponent(jScrollPane1))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addGroup(layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                  .addComponent(nameTextField)
                  .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
                  .addGroup(layout.createSequentialGroup()
                    .addComponent(addressTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                      .addComponent(settingsButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                      .addComponent(portTextField)))))
              .addGroup(layout.createSequentialGroup()
                .addGap(13, 13, 13)
                .addComponent(sendButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(addButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))))
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
          .addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
          .addComponent(jScrollPane3))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
          .addGroup(layout.createSequentialGroup()
            .addComponent(nameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(14, 14, 14)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
              .addComponent(addressTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addComponent(portTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(addButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addComponent(sendButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addComponent(settingsButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
          .addComponent(jScrollPane1))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(listeningPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(startListeningButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addContainerGap(39, Short.MAX_VALUE))
    );

    listeningPort.getAccessibleContext().setAccessibleName("listeningPort");
    startListeningButton.getAccessibleContext().setAccessibleName("startListeningButton");

    pack();
  }// </editor-fold>//GEN-END:initComponents

    private void sendButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_sendButtonActionPerformed
    {//GEN-HEADEREND:event_sendButtonActionPerformed
		JPanel currentPanel = ( JPanel ) tabbedPane.getSelectedComponent();
		for ( Conversation conversation : Conversations.getInstance().getConversations() )
		{
			if ( conversation.getPanel().equals(currentPanel) )
			{
				conversation.getTransportEndpoint().sendMessage(
								messageTextArea.getText().getBytes());
				conversation.updateConversation(Creditentials.getInstance().getContact(),
																				messageTextArea.getText());
				messageTextArea.setText("");
				break;
			}
		}

    }//GEN-LAST:event_sendButtonActionPerformed

    private void addressTextFieldActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_addressTextFieldActionPerformed
    {//GEN-HEADEREND:event_addressTextFieldActionPerformed
		// TODO add your handling code here:
    }//GEN-LAST:event_addressTextFieldActionPerformed

    private void portTextFieldActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_portTextFieldActionPerformed
    {//GEN-HEADEREND:event_portTextFieldActionPerformed
		// TODO add your handling code here:
    }//GEN-LAST:event_portTextFieldActionPerformed

    private void addButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_addButtonActionPerformed
    {//GEN-HEADEREND:event_addButtonActionPerformed
		try
		{
			Contact contact = new Contact(InetAddress.getByName(
							addressTextField.getText()), Integer.parseInt(
							portTextField.getText()), nameTextField.getText());
			Contacts.getInstance().getContacts().add(contact);
			contactsListModel.addElement(contact);
		}
		catch ( UnknownHostException e )
		{
		}
    }//GEN-LAST:event_addButtonActionPerformed

    private void contactListMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_contactListMouseClicked
    {//GEN-HEADEREND:event_contactListMouseClicked
		Conversation conversation;
		try
		{
			conversation = new Conversation(
							( Contact ) (contactList.getSelectedValue()));
			Conversations.getInstance().getConversations().add(conversation);
			tabbedPane.addTab(conversation.getContact().getName(),
												conversation.getPanel());
			tabbedPane.setPreferredSize(new Dimension(300, 400));
			Executors.newCachedThreadPool(Executors.defaultThreadFactory()).execute(
							conversation);
		}
		catch ( SrtpException ex )
		{
			Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
		}

    }//GEN-LAST:event_contactListMouseClicked

    private void settingsButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_settingsButtonActionPerformed
    {//GEN-HEADEREND:event_settingsButtonActionPerformed
		javax.swing.JDialog dialog = new SettingsJForm(this, false);
		dialog.setVisible(true);
    }//GEN-LAST:event_settingsButtonActionPerformed

  private void startListeningButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_startListeningButtonActionPerformed
  {//GEN-HEADEREND:event_startListeningButtonActionPerformed
		if ( !serverRunned )
		{
			serverRunned = true;
			startListeningButton.setEnabled(false);
			executorService.execute(new Runnable()
			{
				@Override
				public void run()
				{
					try
					{
						ConversationListener listener = new ConversationListener(InetAddress.getLocalHost(),
																																		 Integer.parseInt(listeningPort.getText()),
																																		 10);
						while ( true )
						{
							IDataTransportable communicationEndpoint = listener.acceptConnection();
							Conversation conversation = new Conversation(communicationEndpoint);
							tabbedPane.addTab(conversation.getContact().getName(), conversation.getPanel());
							Conversations.getInstance().getConversations().add(conversation);
							executorService.execute(conversation);
						}
					}
					catch ( UnknownHostException ex )
					{
						Logger.getLogger(Program.class.getName()).log(Level.SEVERE,
																													null, ex);
					}
					catch ( IOException ex )
					{
						Logger.getLogger(Program.class.getName()).log(Level.SEVERE,
																													null, ex);
					}
					catch ( SrtpException ex )
					{
						Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
					}

				}
			});
		}

  }//GEN-LAST:event_startListeningButtonActionPerformed

  private void listeningPortActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_listeningPortActionPerformed
  {//GEN-HEADEREND:event_listeningPortActionPerformed
		// TODO add your handling code here:
  }//GEN-LAST:event_listeningPortActionPerformed
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private java.awt.Button addButton;
  private javax.swing.JTextField addressTextField;
  private javax.swing.JList contactList;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JScrollPane jScrollPane3;
  private java.awt.TextField listeningPort;
  private javax.swing.JTextArea messageTextArea;
  private javax.swing.JTextField nameTextField;
  private javax.swing.JTextField portTextField;
  private java.awt.Button sendButton;
  private java.awt.Button settingsButton;
  private java.awt.Button startListeningButton;
  private javax.swing.JTabbedPane tabbedPane;
  // End of variables declaration//GEN-END:variables
}
